<?php
/**
 * Created by PhpStorm.
 * User: sks
 * Date: 2015/12/15
 * Time: 13:45
 */

/**
 * Class AdminService
 */

class AdminService extends BaseService{

    private static $self = NULL;

    /**
     * @return AdminService
     */
   static public function instance()
   {
        if(self::$self == NULL){
            self::$self = new self;}
        return self::$self;
    }

    /**************** Model ******************/

    /**
     * @var Involved_AdminModel
     */
    private $mAdmin             =   NULL;
    private $mProduct           =   NULL;
    private $mProduct_cate      =   NULL;
    private $mProduct_pic       =   NULL;
    private $mLevel             =   NULL;
    private $mSupplier          =   NULL;
    private $mPlace             =   NULL;
    private $mBrand             =   NULL;

    public function __construct()
    {
        $this->mAdmin           =    new Involved_AdminModel();
        $this->mProduct         =    new Involved_ProductModel();
        $this->mProduct_cate    =    new Involved_ProductCateModel();
        $this->mProduct_pic     =    new Involved_ProductPicModel();
        $this->mLevel           =    new Involved_LevelModel();
        $this->mSpec            =    new Involved_SpecModel();
        $this->mSupplier        =    new Involved_SupplierModel();
        $this->mPlace           =    new Involved_PlaceModel();
        $this->mBrand            =    new Involved_ProductBrandModel();
    }

    /**
     * 产品录入
     * @param $paramObj
     * @return int
     * @throws Exception
     */
    public function ImportProduct($paramObj)
    {
        #参数验证
        $check = ToolKit::checkProperties($paramObj,['product_name', 'stock', 'brand_id', 'quality',
            'price','unit', 'description', 'place', 'spec', 'level', 'storage', 'start_num',
            'is_index', 'is_up', 'product_img']);
        if (!$check)
            throw new Exception('参数不足', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);

        #图片上传
        $quality                    =   $this->mProduct_cate->GetProductQuality($paramObj->quality);
        if (!$quality)
            throw new Exception('材质ID错误', ErrorCodeEnum::STATUS_ERROR);
        $paramObj->classes          =   $this->mProduct_cate->GetParentCate($paramObj->quality);
        $paramObj->category         =   $this->mProduct_cate->GetParentCate($paramObj->classes);
        $paramObj->product_img      =   QiniuUpload::instance()->upload_files($paramObj->product_img);

        #数据汇总
        $aData = [
            'product_name'  =>  $paramObj->product_name,
            'product_sn'    =>  $paramObj->product_sn,
            'stock'         =>  $paramObj->stock,
            'brand_id'      =>  $paramObj->brand_id,
            'quality'       =>  $paramObj->quality,
            'classes'       =>  $paramObj->classes,
            'category'      =>  $paramObj->category,
            'price'         =>  $paramObj->price,
            'unit'          =>  $paramObj->unit,
            'brief'         =>  $paramObj->brief,
            'description'   =>  $paramObj->description,
            'place'         =>  $paramObj->place,
            'spec'          =>  $paramObj->spec,
            'level'         =>  $paramObj->level,
            'storage'       =>  $paramObj->storage,
            'start_num'     =>  $paramObj->start_num,
            'channel_id'    =>  $paramObj->channel_id,
            'is_self_support' =>  1,
            'is_index'      =>  $paramObj->is_index,
            'is_up'         =>  $paramObj->is_up,
            'product_img'   =>  $paramObj->product_img,
            'created'       =>  time()
        ];
        $product_id         =   $this->mProduct->insert($aData);

        #详情图
        if(!empty($paramObj->show_img1)){
            $paramObj->show_img1 = QiniuUpload::instance()->upload_files($paramObj->show_img1);
        }
        if(!empty($paramObj->show_img2)){
            $paramObj->show_img2 = QiniuUpload::instance()->upload_files($paramObj->show_img2);
        }
        if(!empty($paramObj->show_img3)){
            $paramObj->show_img3 = QiniuUpload::instance()->upload_files($paramObj->show_img3);
        }

        $aData = [
            'product_id'    =>  $product_id,
            'show_img1'     =>  $paramObj->show_img1,
            'show_img2'     =>  $paramObj->show_img2,
            'show_img3'     =>  $paramObj->show_img3,
            'created'       =>  time()
        ];

        return $this->mProduct_pic->insert($aData);
    }

    /**
     * 等级录入
     * @param $paramObj
     * @return int
     * @throws Exception
     */
    public function ImportProductLevel($paramObj)
    {
        #参数验证
        $check = ToolKit::checkProperties($paramObj,['level_name', 'quality', 'sort_by']);
        if (!$check)
            throw new Exception('参数不足', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);

        #数据存储
        $aData = [
            'level_name'     =>  $paramObj->level_name,
            'quality'        =>  $paramObj->quality,
            'sort_by'        =>  $paramObj->sort_by,
        ];

        return $this->mLevel->insert($aData);
    }

    /**
     * 规格录入
     * @param $paramObj
     * @return int
     * @throws Exception
     */
    public function ImportProductSpec($paramObj)
    {
        #参数验证
        $check = ToolKit::checkProperties($paramObj,['spec_name', 'quality', 'sort_by']);
        if (!$check)
            throw new Exception('参数不足', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);

        #数据存储
        $aData = [
            'spec_name'      =>  $paramObj->spec_name,
            'quality'        =>  $paramObj->quality,
            'sort_by'        =>  $paramObj->sort_by,
        ];

        return $this->mSpec->insert($aData);
    }

    /**
     * 获取等级信息
     * @param $quality
     * @return array
     */
    public function GetLevelInfo($quality)
    {
        $this->mLevel->setSelect(['level_id','level_name']);
        return $this->mLevel->fetchAll(['quality' => $quality], [], ['sort_by'=>'asc']);
    }

    /**
     * 获取等级信息
     * @param $quality
     * @return array
     */
    public function GetSpecInfo($quality)
    {
        $this->mSpec->setSelect(['spec_id','spec_name']);
        return $this->mSpec->fetchAll(['quality' => $quality], [], ['sort_by'=>'asc']);
    }

    /**
     * 商家入库
     * @param $paramObj
     * @return int
     * @throws Exception
     * @author buluota
     * @date 2016-03-09
     */
    public function ImportSupplier($paramObj)
    {
        #参数验证
        $check = ToolKit::checkProperties($paramObj,['supplier_name', 'owner', 'company','address','brief']);
        if (!$check)
            throw new Exception('参数不足', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);

        #注册用户
        $insert_user = array(
            'user_name'     =>  $paramObj->owner,
            'avatar'		=>  'http://media.mutouw.com/profile.png',
            'created'   	=>  time(),
        );
        $user_id = $this->mUser->insert($insert_user);

        #t图片上传
        if(!empty($paramObj->operate_license)) {
            $paramObj->operate_license = QiniuUpload::instance()->upload_files($paramObj->operate_license);
        }
        if(!empty($paramObj->tax_license)) {
            $paramObj->tax_license = QiniuUpload::instance()->upload_files($paramObj->tax_license);
        }
        if(!empty($paramObj->show_img1)) {
            $paramObj->show_img1 = QiniuUpload::instance()->upload_files($paramObj->show_img1);
        }
        if(!empty($paramObj->show_img2)) {
            $paramObj->show_img2 = QiniuUpload::instance()->upload_files($paramObj->show_img2);
        }
        if(!empty($paramObj->show_img3)) {
            $paramObj->show_img3 = QiniuUpload::instance()->upload_files($paramObj->show_img3);
        }

        #数据存储
        $aData = [
            'supplier_id'           =>  $user_id,
            'supplier_name'         =>  $paramObj->supplier_name,
            'owner'                 =>  $paramObj->owner,
            'company'               =>  $paramObj->company,
            'brand'                 =>  $paramObj->brand,
            'scale'                 =>  $paramObj->scale,
            'address'               =>  $paramObj->address,
            'phone'                 =>  $paramObj->phone,
            'id_card'               =>  $paramObj->id_card,
            'bank_account'          =>  $paramObj->bank_account,
            'bank_number'           =>  $paramObj->bank_number,
            'operate_license'       =>  $paramObj->operate_license,
            'tax_license'           =>  $paramObj->tax_license,
            'show_img1'             =>  $paramObj->show_img1,
            'show_img2'             =>  $paramObj->show_img2,
            'show_img3'             =>  $paramObj->show_img3,
            'business_scope'        =>  $paramObj->business_scope,
            'market'                =>  $paramObj->market,
            'brief'                 =>  $paramObj->brief,
            'feature'               =>  $paramObj->feature,
            'storage'               =>  $paramObj->storage,
            'is_foreign'            =>  $paramObj->is_foreign,
        ];

        return $this->mSupplier->insert($aData);
    }

    /**
     * 商家入库
     * @return int
     * @throws Exception
     * @author buluota
     * @date 2016-03-09
     */
    public function GetProductBoard()
    {
        $result =  $this->mProduct->GetProductBoard();
        foreach($result as &$product){
            $product->is_up         =   ($product->is_up == 1) ? '上架' : '下架';
            $product->supplier_name =   empty($product->supplier_name) ?  '自营' : $product->supplier_name;
        }
        return $result;
    }

    /**
     * 产地入库
     * @param $paramObj
     * @throws Exception
     * @author buluota
     * @date 2016-03-09
     */
    public function ImportProductPlace($paramObj)
    {
        #参数验证
        $check = ToolKit::checkProperties($paramObj,['place_name']);
        if (!$check)
            throw new Exception('参数不足', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);

        #数据存储
        $aData = [
            'place_name'            =>  $paramObj->place_name,
            'is_foreign'            =>  $paramObj->is_foreign,
        ];

        $this->mPlace->insert($aData);
    }

    /**
     * 产地管理
     * @author buluota
     * @date 2016-03-09
     */
    public function GetPlaceList()
    {
        return $this->mPlace->fetchAll([],[],['place_id' => 'asc']);
    }

    /**
     * 品牌录入
     * @param $paramObj
     * @return int
     * @throws Exception
     * @author buluota
     * @date 2016-03-10
     */
    public function ImportProductBrand($paramObj)
    {
        #参数验证
        $check = ToolKit::checkProperties($paramObj,['brand_name']);
        if (!$check)
            throw new Exception('参数不足', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);

        #图片上传
        if(!empty($paramObj->brand_img))
            $paramObj->brand_img    =   QiniuUpload::instance()->upload_files($paramObj->brand_img);

        $aData  =   [
            'brand_name'    =>  $paramObj->brand_name,
            'quality'       =>  $paramObj->quality,
            'brand_img'     =>  $paramObj->brand_img,
            'is_show'       =>  $paramObj->is_show,
        ];

        return $this->mBrand->insert($aData);
    }

    /**
     * 品牌管理
     * @return int
     * @throws Exception
     * @author buluota
     * @date 2016-03-10
     */
    public function GetBrandList()
    {
        $brand_list =  $this->mBrand->GetBrandList();
        foreach($brand_list as &$b)
        {
            $b->is_show     =   ($b->is_show == 1) ? "展示" : "隐藏";
            $b->quality     =   empty($b->cate_name) ? "暂无" : $b->cate_name;
        }
        return $brand_list;
    }

    public function GetSupplierList()
    {

//        $this->mSupplier->setSelect(['supplier_id','supplier_name','market','owner','phone',
//        'brand']);
    }

    /**
     * 管理员管理
     * @return mixed
     */
    public function ManageAdmin()
    {
        return $this->mAdmin->GetAdminList();
    }
    /**
     * @return admin one info
     */
    public function getAdminOne($id)
    {
        return $this->mAdmin->getAdminOneInfo($id);
    }
    public function addAdminInfo($admin)
    {
        $aData = [
            'name'          =>     $admin->name,
            'real_name'     =>     $admin->real_name,
            'password'      =>     $admin->password,
            'role_id'       =>     $admin->role_id,
            'mobile'        =>     $admin->mobile,
            'status'        =>     $admin->status,
            'created'       =>     $admin->created,
        ];

       return  $this->mAdmin->insert($aData);
    }

    public function editAdminInfo($admin,$id)
    {
        $aData = [
            'name'          =>     $admin->name,
            'real_name'     =>     $admin->real_name,
            'role_id'       =>     $admin->role_id,
            'password'      =>     $admin->password,
            'mobile'        =>     $admin->mobile,
            'status'        =>     $admin->status,
            'created'       =>     $admin->created,
        ];

        return  $this->mAdmin->update($aData,['id'=>$id]);
    }

    public function deleteAdminInfo($id){

        return $this->mAdmin->delete(['id'=>$id]);
    }

    /**
     * 验证用户
     * @param $user
     * @return bool|VO_Common|VO_Response_DimStuff
     * @throws Exception
     */
    public function LoginValidator($user)
    {
        #此处只做简单验证
        if(empty($user->username) || empty($user->password)){
            throw new Exception('必填项不能为空', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }
        if(strtolower($user->captcha) != strtolower(Session::get('mt_Captcha'))){
            throw new Exception('验证码错误', ProfessionErrorCodeEnum::ERROR_VERIFICATION_CODE_WRONG);
        }

        #数据验证
        $admin_info = $this->mAdmin->getLoginAdminInfo($user->username,$user->password);
        if(!$admin_info){
            throw new Exception('密码错误', ProfessionErrorCodeEnum::ERROR_PASSWORD_WRONG);
        }

        #存储SESSION
        Session::put(UserEnum::ADMIN_USER_KEY, $admin_info);

        return $admin_info;
    }

}